from contextlib import asynccontextmanager

from fastapi import FastAPI, HTTPException, Body
from pydantic import BaseModel
from bilibili_api import live, Credential
from MultiRoomMonitor import MultiRoomMonitor
import asyncio

# 请求体模型
from llm_直播弹幕.DatabaseManager import DatabaseManager
# from llm_直播弹幕.PersistenceService import PersistenceService
from llm_直播弹幕.redis.RedisManager import RedisManager
from llm_直播弹幕.PersistenceServiceNew import PersistenceService

class StartRequest(BaseModel):
    room_ids: list[int]

DB_URL = "mysql+aiomysql://root:111111@localhost/gardevoir"
# FastAPI应用初始化
# app = FastAPI()
credential = Credential(
    sessdata="6b1a13d7%2C1758939876%2C8951f%2A31CjCnuNCNztCftrPkFjag8k47dIuQZ-ut62XXcemFADFMuB25dQCJqC6nM4LKkTq7fpYSVlo0ZFNkVmVXcWhlcXhXS3hCOXZBYjYyVXdJZ0ZSNllfWFJ3T3VBZEVfUkxxNFJrNU4xd1BZNVAxcEVOc3JFUUNubV8tc045c0ZsaXR2NkMtVjFQZU1nIIEC",
    bili_jct="0fe3dcb51de2f49bea0458875ba9c957",
    buvid3="21386F8E-E6CB-6015-D6CB-63F5C751BB9751434infoc",
    dedeuserid="3546869426817357")
# app.state.monitor = MultiRoomMonitor(credential)


@asynccontextmanager
async def lifespan(app: FastAPI):
    # 初始化组件
    redis_mgr = RedisManager()
    db_mgr = DatabaseManager(DB_URL)
    await redis_mgr.init_pool()

    # 初始化监控器并注入 Redis
    monitor = MultiRoomMonitor(credential, redis_mgr=redis_mgr)

    # 初始化持久化服务
    persistence = PersistenceService(redis_mgr, db_mgr)
    persistence_task = asyncio.create_task(persistence.start_consuming())

    # 存储到 app 状态
    app.state.monitor = monitor
    app.state.persistence = persistence

    yield  # 进入运行状态

    # 关闭时清理
    persistence_task.cancel()
    await redis_mgr.close()
    await db_mgr.engine.dispose()

app = FastAPI(lifespan=lifespan)
@app.post("/monitor/start")
async def start_monitoring(request: StartRequest = Body(...)):
    """启动监听服务（兼容原有参数）"""
    if app.state.monitor._running:
        raise HTTPException(400, "服务已在运行中")

    try:
        # 创建异步任务运行原有启动逻辑
        asyncio.create_task(app.state.monitor.start(request.room_ids))
        return {
            "status": "starting",
            "rooms": request.room_ids
        }
    except Exception as e:
        raise HTTPException(500, f"启动失败: {str(e)}")


@app.post("/monitor/stop")
async def stop_monitoring():
    """停止监听服务"""
    await app.state.monitor.stop()
    return {"status": "stopped"}


@app.post("/rooms/add")
async def add_room(room_id: int = Body(..., embed=True)):
    """添加单个房间"""
    try:
        await app.state.monitor.add_room(room_id)
        return {"action": "added", "room_id": room_id}
    except Exception as e:
        raise HTTPException(500, str(e))


@app.get("/status")
async def get_status():
    """获取完整状态"""
    return {
        "running": app.state.monitor._running,
        "rooms": list(app.state.monitor.rooms.keys()),
        "connection_count": len(app.state.monitor.tasks)
    }


if __name__ == "__main__":
    import uvicorn

    uvicorn.run(app, host="127.0.0.1", port=9980)